package com.g2.admin.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.g2.admin.dao.mapper.IAuthAuthorityMapper;
import com.g2.admin.model.po.AuthAuthorityPo;
import com.g2.admin.model.to.AuthTreeTo;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

@Service
@Slf4j
public class AuthAuthorityService {
    @Autowired
    private IAuthAuthorityMapper authauthorityMapper;

    public AuthAuthorityPo getAuthauthority(long id) {
        return authauthorityMapper.selectById(id);
    }

    public void delAuthauthority(long id) {
        authauthorityMapper.deleteById(id);
    }

    public void addAuthauthority(AuthAuthorityPo authauthority) {
        authauthorityMapper.insert(authauthority);
    }

    public void updateAuthauthority(AuthAuthorityPo authauthority) {
        // 不能改编码
        authauthority.setCode(null);
        authauthorityMapper.updateById(authauthority);
    }

    public List<AuthAuthorityPo> getAuthByCode(Set<String> codes) {
        return authauthorityMapper.selectList(new QueryWrapper<AuthAuthorityPo>().lambda().select(AuthAuthorityPo::getCode, AuthAuthorityPo::getHref)
                .in(AuthAuthorityPo::getCode, codes));
    }

    /**
     * 获取所有权限列表，并组装为树形结构
     */
    public List<AuthAuthorityPo> getAuthTree(String sysCode) {
        List<AuthAuthorityPo> authoritys = authauthorityMapper.selectList(new QueryWrapper<AuthAuthorityPo>().lambda().eq(AuthAuthorityPo::getSystemCode, sysCode));
        if (CollectionUtils.isEmpty(authoritys)) {
            return null;
        }
        // 先把非第一级的权限分类
        Map<String, List<AuthAuthorityPo>> authMap = authoritys.stream().filter(x -> StringUtils.isNotEmpty(x.getParentCode()))
                .collect(Collectors.toMap(AuthAuthorityPo::getParentCode,
                        x -> Lists.newArrayList(x), (List<AuthAuthorityPo> n, List<AuthAuthorityPo> o) -> {
                            n.addAll(o);
                            return n;
                        }));
        authoritys.forEach(x->x.setChildren(authMap.get(x.getCode())));
        // 处理一级权限
        List<AuthAuthorityPo> result = authoritys.stream().filter(x -> StringUtils.isEmpty(x.getParentCode()))
                .collect(Collectors.toList());
        return result;
    }

    private QueryWrapper<AuthAuthorityPo> getQw(String systemCode) {
        QueryWrapper<AuthAuthorityPo> qw = new QueryWrapper<>();
        qw.lambda().eq(AuthAuthorityPo::getSystemCode, systemCode)
                .orderByDesc(AuthAuthorityPo::getSort);
        return qw;
    }

}
